﻿using System;
using System.Collections.Generic;
using System.Linq;
using Fuse8.ContentManagementFramework.Web.Etc;

namespace Fuse8.ContentManagementFramework.Administration.Models
{
    [Serializable]
    public class PageTreeHistory
    {
        private PageTreeHistory()
        {
            Items = new List<PageTreeHistoryItem>().ToArray();
        }

        public PageTreeHistoryItem[] Items { get; protected set; }

        public static PageTreeHistory Current
        {
            get
            {
                var current = new StorageFacade<PageTreeHistory>().GetProperty() ?? new PageTreeHistory();
                return current;
            }
        }

        public void Open(int pageId)
        {
            Close(pageId, true);
            List<PageTreeHistoryItem> list = Current.Items.ToList();
            list.Add(new PageTreeHistoryItem() {Id = pageId, IsOpen = true});
            Save(list);
        }

        public void Close(int pageId, bool notSave = false)
        {
            List<PageTreeHistoryItem> list = Current.Items.ToList();
            list.RemoveAll(p => p.Id == pageId);
            if (!notSave)
            {
                Save(list);
            }
        }

        private void Save(List<PageTreeHistoryItem> list)
        {
            new StorageFacade<PageTreeHistory>().SetProperty(new PageTreeHistory() {Items = list.ToArray()});
        }

        public bool IsOpen(int pageId)
        {
            return Current.Items.Any(p => p.Id == pageId && p.IsOpen);
        }        
    }

    [Serializable]
    public class PageTreeHistoryItem
    {
        public int Id { get; set; }
        public bool IsOpen { get; set; }
    }
}